import React, {Component} from 'react';
import {connect} from 'dva';
import {Link} from 'dva/router';
import {Checkbox, Alert, Icon} from 'antd';
import Login from './../../components/Login';
import styles from './Login.less';

const {Tab, UserName, Password, Mobile, Captcha, Submit} = Login;

@connect(({user, loading}) => ({
  user,
  submitting: loading.effects['user/login'],
}))
export default class LoginPage extends Component {
  state = {
    qrcode: false,
    type: 'account',
    autoLogin: true,
  };

  onTabChange = type => {
    this.setState({type});
  };

  handleSubmit = (err, values) => {

    const {type} = this.state;
    if (!err) {
      this.props.dispatch({
        type: 'user/login',
        payload: {
          ...values,
          type,
        },
      });
    }
  };

  changeAutoLogin = e => {
    this.setState({
      autoLogin: e.target.checked,
    });
  };

  renderMessage = content => {
    return <Alert style={{marginBottom: 24}} message={content} type="error" showIcon/>;
  };

  render() {
    const {user, submitting} = this.props;
    const {type} = this.state;
    return (
      <div className={styles.main}>
        <Login defaultActiveKey={type} onTabChange={this.onTabChange} onSubmit={this.handleSubmit}>
          <Tab key="account" tab="账户密码登录">
            {user.status === 'error' &&
            user.type === 'account' &&
            !submitting &&
            this.renderMessage('账户或密码错误!')}
            <UserName name="username" placeholder="请输入用户名"/>
            <Password name="password" placeholder="请输入账号密码"/>
          </Tab>
          <Tab key="mobile" tab="手机号登录">
            {user.status === 'error' &&
            user.type === 'mobile' &&
            !submitting &&
            this.renderMessage('验证码错误')}
            <Mobile name="mobile" placeholder="请输入手机号码"/>
            <Captcha name="captcha" placeholder="请输入验证码"/>
          </Tab>
          <div>
            <Checkbox checked={this.state.autoLogin} onChange={this.changeAutoLogin}>
              自动登录
            </Checkbox>
            <a style={{float: 'right'}} href="">
              忘记密码
            </a>
          </div>
          <Submit loading={submitting}>登录</Submit>
          <div className={styles.other}>
            <Link className={styles.qrcode} to="/user/register">
              使用二维码登录
            </Link>
            <Link className={styles.register} to="/user/register">
              注册账户
            </Link>
          </div>
        </Login>
      </div>
    );
  }
}
